package com.zzg.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzg.srb.base.utils.JwtUtils;
import com.zzg.srb.common.Enum.DefaultImageUrlEnum;
import com.zzg.srb.common.Enum.UserStateEnum;
import com.zzg.srb.common.exception.Assert;
import com.zzg.srb.common.result.ResponseEnum;
import com.zzg.srb.common.utils.MD5;
import com.zzg.srb.core.entity.pojo.UserAccount;
import com.zzg.srb.core.entity.pojo.UserInfo;
import com.zzg.srb.core.entity.pojo.UserLoginRecord;
import com.zzg.srb.core.entity.query.UserInfoQuery;
import com.zzg.srb.core.entity.vo.LoginVo;
import com.zzg.srb.core.entity.vo.RegisterVo;
import com.zzg.srb.core.entity.vo.UserIndexVo;
import com.zzg.srb.core.entity.vo.UserInfoVo;
import com.zzg.srb.core.mapper.UserAccountMapper;
import com.zzg.srb.core.mapper.UserInfoMapper;
import com.zzg.srb.core.mapper.UserLoginRecordMapper;
import com.zzg.srb.core.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author zhengzg
 * @since 2022-05-27
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Resource
    private UserAccountMapper userAccountMapper;

    @Resource
    private UserLoginRecordMapper userLoginRecordMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(RegisterVo registerVo) {
        //判断用户是否已经注册
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getMobile,registerVo.getMobile());
        Long count = baseMapper.selectCount(queryWrapper);
        Assert.isTrue(count == 0, ResponseEnum.MOBILE_EXIST_ERROR);

        //插入用户信息记录：userInfo
        UserInfo userInfo = new UserInfo();
        userInfo.setUserType(registerVo.getUserType());
        userInfo.setNickName(registerVo.getMobile());
        userInfo.setName(registerVo.getMobile());
        userInfo.setMobile(registerVo.getMobile());
        //使用MD5对密码尽心加密
        userInfo.setPassword(MD5.encrypt(registerVo.getPassword()));
        userInfo.setStatus(UserStateEnum.STATUS_NORMAL.getValue());
        userInfo.setHeadImg(DefaultImageUrlEnum.DEFAULTIMAGE.getUrl());
        baseMapper.insert(userInfo);

        //插入用户账户记录：user_account
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userInfo.getId());
        userAccountMapper.insert(userAccount);
    }

    @Override
    public UserInfoVo login(LoginVo loginVo, String ip) {

        //用户是否存在
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(UserInfo::getMobile,loginVo.getMobile())
                .eq(UserInfo::getUserType,loginVo.getUserType());
        UserInfo userInfo = baseMapper.selectOne(queryWrapper);
        Assert.notNull(userInfo,ResponseEnum.LOGIN_MOBILE_ERROR);

        //密码是否正确
        Assert.equals(MD5.encrypt(loginVo.getPassword()),userInfo.getPassword(),ResponseEnum.LOGIN_PASSWORD_ERROR);

        //用户是否被禁用
        Assert.equals(userInfo.getStatus(),UserStateEnum.STATUS_NORMAL.getValue(),ResponseEnum.LOGIN_LOKED_ERROR);

        //记录登录日志
        UserLoginRecord userLoginRecord = new UserLoginRecord();
        userLoginRecord.setUserId(userInfo.getId());
        userLoginRecord.setIp(ip);
        userLoginRecordMapper.insert(userLoginRecord);

        //生成token
        String token = JwtUtils.createToken(userInfo.getId(), userInfo.getName());

        //组合token
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        userInfoVo.setToken(token);

        return userInfoVo;
    }

    @Override
    public IPage<UserInfo> listPage(Page<UserInfo> userInfoPage, UserInfoQuery userInfoQuery) {
        if (userInfoQuery == null) {
            return baseMapper.selectPage(userInfoPage, null);
        }
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(userInfoQuery.getStatus() != null,UserInfo::getUserType,userInfoQuery.getUserType())
                .eq(StringUtils.isNoneBlank(userInfoQuery.getMobile()),UserInfo::getMobile,userInfoQuery.getMobile())
                .eq(userInfoQuery.getStatus() != null,UserInfo::getStatus,userInfoQuery.getStatus());
        return baseMapper.selectPage(userInfoPage, queryWrapper);
    }

    @Override
    public Integer lock(UserInfo userInfo) {
        return baseMapper.updateById(userInfo);
    }

    @Override
    public boolean checkMobile(String mobile) {
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getMobile,mobile);
        Long count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }

    @Override
    public UserIndexVo getIndexUserInfo(Long userId) {
        //用户信息
        UserInfo userInfo = baseMapper.selectById(userId);

        //账户信息
        QueryWrapper<UserAccount> userAccountQueryWrapper = new QueryWrapper<>();
        userAccountQueryWrapper.eq("user_id", userId);
        UserAccount userAccount = userAccountMapper.selectOne(userAccountQueryWrapper);

        //登录信息
        QueryWrapper<UserLoginRecord> userLoginRecordQueryWrapper = new QueryWrapper<>();
        userLoginRecordQueryWrapper
                .eq("user_id", userId)
                .orderByDesc("id")
                .last("limit 1");
        UserLoginRecord userLoginRecord = userLoginRecordMapper.selectOne(userLoginRecordQueryWrapper);

        //组装结果数据
        UserIndexVo userIndexVO = new UserIndexVo();
        userIndexVO.setUserId(userInfo.getId());
        userIndexVO.setUserType(userInfo.getUserType());
        userIndexVO.setName(userInfo.getName());
        userIndexVO.setNickName(userInfo.getNickName());
        userIndexVO.setHeadImg(userInfo.getHeadImg());
        userIndexVO.setBindStatus(userInfo.getBindStatus());
        userIndexVO.setAmount(userAccount.getAmount());
        userIndexVO.setFreezeAmount(userAccount.getFreezeAmount());
        userIndexVO.setLastLoginTime(userLoginRecord.getCreateTime());

        return userIndexVO;
    }

    @Override
    public String getMobileByBindCode(String bindCode) {
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("bind_code", bindCode);
        UserInfo userInfo = baseMapper.selectOne(userInfoQueryWrapper);
        return userInfo.getMobile();
    }
}
